package com.emep.changzhi.analyse.service.basics;

import com.emep.changzhi.analyse.entity.basics.SysCompanyInfo;
import com.emep.changzhi.analyse.repository.basics.SysCompanyInfoRepository;
import com.emep.changzhi.analyse.repository.outlet.SysOutletInfoRepository;
import com.emep.changzhi.analyse.entity.basics.*;
import com.emep.changzhi.analyse.repository.basics.*;
import com.emep.changzhi.analyse.utils.Constant;
import com.emep.changzhi.analyse.utils.MapUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

/**
 * @author Wangcc
 * @version V1.0
 * @Description: 企业信息业务层
 * @date 2018/2/27 16:00
 */
@Service
@Slf4j
public class SysCompanyInfoService {
    
    @Resource
    private SysCompanyInfoRepository sysCompanyInfoRepository;

    @Resource
    private SysRegionInfoRepository sysRegionInfoRepository;

    @Resource
    private SysKeyTypeRepository sysKeyTypeRepository;

    @Resource
    private SysAreaInfoRepository sysAreaInfoRepository;

    @Resource
    private SysIndustryTypeRepository sysIndustryTypeRepository;

    /**
     *
     * 不含查询条件的分页获取数据
     *
     * @param pageNo
     * @param pageSize
     * @return
     * @throws Exception
     */
    public Page<SysCompanyInfo> findAll(Integer pageNo, Integer pageSize){
        try {
            Pageable pageable = new PageRequest(pageNo-1, pageSize);
            return sysCompanyInfoRepository.findAll(pageable);
        } catch (Exception e) {
            log.error(e.getClass().getName()+":"+ e.getMessage());
            log.error(e.getLocalizedMessage());
            return null;
        }
    }

    /**
     *
     * 新增企业
     *
    private Set<SysRegionInfo> sysRegionInfos = new HashSet<>();

     private Set<SysKeyTypeInfo> sysKeyTypeInfos = new HashSet<>();

     private Set<SysIndustryTypeInfo> sysIndustryTypeInfos = new HashSet<>();

     private Set<SysAreaInfo> sysAreaInfos = new HashSet<>();
     *
     * @param payload
     * @return
     * @throws Exception
     */
    public SysCompanyInfo save(Map<String, Object> payload) {
        SysCompanyInfo SysCompanyInfo = null;
        try {
            SysCompanyInfo SysCompanyInfo1 = (SysCompanyInfo) MapUtils.convertMap(SysCompanyInfo.class,payload);

            SysCompanyInfo = sysCompanyInfoRepository.save(SysCompanyInfo1);
        }catch (Exception e){
            log.error(e.getClass().getName()+":"+ e.getMessage());
            log.error(e.getLocalizedMessage());
        }
        return SysCompanyInfo;
    }
    public boolean update(SysCompanyInfo info){
        List<SysCompanyInfo> infos =sysCompanyInfoRepository.findAllByCompanyNameAndIdIsNotAndIsDelete(info.getCompanyName(),info.getId(), Constant.RESULT_DELETECODE_NO);
        if(infos.isEmpty()){
            sysCompanyInfoRepository.save(info);
            return true;
        }
        return false;
    }

    /**
     *
     * 根据id查询企业信息
     *
     * @param id
     * @return
     */
    public SysCompanyInfo findId(String id){
        SysCompanyInfo SysCompanyInfo = null;
        try {
            SysCompanyInfo = sysCompanyInfoRepository.findSysCompanyInfoById(id);
        }catch (Exception e){
            log.error(e.getClass().getName()+":"+ e.getMessage());
            log.error(e.getLocalizedMessage());
        }
        return SysCompanyInfo;
    }

    /**
     *
     * 根据id 删除企业
     *
     * @param id
     */
    public Boolean delete(String id) {
        Boolean result = false;
        try {
            Integer  result1 = sysCompanyInfoRepository.deleteSysCompanyInfoById(id);
            if(result1 == 1){
                result = true;
            }
        }catch (Exception e){
            log.error(e.getClass().getName()+":"+ e.getMessage());
            log.error(e.getLocalizedMessage());
        }
        return result;
    }

    /**
     *查询所有企业
     *
     * @return
     */
    public List<SysCompanyInfo> list() {
        List<SysCompanyInfo> SysCompanyInfos = null;
        try {
            SysCompanyInfos =  sysCompanyInfoRepository.findAll();
        }catch (Exception e){
            log.error(e.getClass().getName()+":"+ e.getMessage());
            log.error(e.getLocalizedMessage());
        }
        return SysCompanyInfos;
    }


    /**
     *
     * @param page 页数
     * @param size 数量
     * @param SysCompanyInfo 参数
     * @return
     */
    public Page<SysCompanyInfo> findBookCriteria(Integer page, Integer size, SysCompanyInfo SysCompanyInfo) {
        //规格定义//页码：前端从1开始，jpa从0开始，做个转换
        Pageable pageable = new PageRequest(page-1,size , Sort.Direction.ASC, "createDate");
        Page<SysCompanyInfo> studentPage = sysCompanyInfoRepository.findAll(new Specification<SysCompanyInfo>(){
            @Override
            public Predicate toPredicate(Root<SysCompanyInfo> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                Predicate p1 = criteriaBuilder.equal(root.get("companyName").as(String.class), SysCompanyInfo.getCompanyName());
                query.where(criteriaBuilder.or(p1));
                return query.getRestriction();
            }
        },pageable);
        return studentPage;
    }


    public Page<SysCompanyInfo> find(int pageIndex, int pageSize, Map<String, Object> params) {

        Page<SysCompanyInfo> epaPage = sysCompanyInfoRepository.findAll(new SysCompanyInfoService.CompanySpec(params),
                PageRequest.of(pageIndex, pageSize, Sort.Direction.ASC, "id"));
        return epaPage;
    }


    private class CompanySpec implements Specification<SysCompanyInfo> {
        private Map<String, Object> params = new HashMap<String, Object>();

        public CompanySpec(Map<String, Object> params) {
            this.params = params;
        }

        @Override
        public Predicate toPredicate(Root<SysCompanyInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            List<Predicate> lstPredicates = new ArrayList<Predicate>();
            if (params.containsKey("isDelete")) {
                lstPredicates.add(cb.like(root.get("isDelete").as(String.class), params.get("isDelete").toString()));
            }
            if (params.containsKey("districtId")) {
                lstPredicates.add(cb.like(root.get("districtId").as(String.class), params.get("districtId").toString()));
            }
            if (params.containsKey("companyName")) {
                lstPredicates.add(cb.like(root.get("companyName").as(String.class), params.get("companyName").toString()));
            }
            Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
            return cb.and(lstPredicates.toArray(arrayPredicates));
        }
    }

}

